//
//  BaseVC.swift
//  MedicalUnionHybrid
//
//  Created by 来 on 2019/9/17.
//  Copyright © 2019 EWell. All rights reserved.
//

import UIKit

class BaseVC: UIViewController {
    
    var isHiddenNavigationBar: Bool = false
    var isHorizontalScreen: Bool = false
    var isScreenPanPopEnabled: Bool = true
    
    lazy var lgf_NavigationBar: LGFNavigationBar = {
        let style = LGFNavigationBarStyle.lgf()
        style.lgf_LeftBtnImageLight = UIImage(named: "nav_back")!
        let bar = LGFNavigationBar.lgf()
        bar.isHidden = true
        bar.lgf_Show(self.view, style: style)
        style.lgf_TitleColor = UIColor.white
        style.lgf_TitleTextFont = UIFont.boldSystemFont(ofSize: 16)
        bar.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(UIDevice.lgf_NavBarH())
        }
        return bar
    }()
    
    /// 标题
    var navTitle: String? {
        didSet {
            self.lgf_NavigationBar.isHidden = false
            self.lgf_NavigationBar.style.lgf_TitleText = navTitle ?? ""
            self.lgf_NavigationBar.lgf_Reload()
            self.lgf_NavigationBar.lgf_LeftButton?.addTarget(self, action: #selector(leftBtnSelect), for: .touchUpInside)
            self.lgf_NavigationBar.lgf_LeftButton?.lgf_AddLong(target: self, action: #selector(leftBtnLongSelect), duration: 0.5)
        }
    }
    
    var rightImage: UIImage! {
        didSet {
            if #available(iOS 10.0, *) {
                rightImage = rightImage.lgf_Resized(to: CGSize.init(width: 25, height: 25))
            } else {
                // Fallback on earlier versions
            }
            self.lgf_NavigationBar.style.lgf_RightBtnImageLight = rightImage
            self.lgf_NavigationBar.style.lgf_ShowRightBtn = true
            self.lgf_NavigationBar.lgf_Reload()
            self.lgf_NavigationBar.lgf_RightButton?.addTarget(self, action: #selector(rightBtnSelect(_:)), for: .touchUpInside)
        }
    }
    
    var rightText: String! {
        didSet {
            self.lgf_NavigationBar.style.lgf_RightBtnTitleText = rightText
            self.lgf_NavigationBar.style.lgf_ShowRightBtn = true
            self.lgf_NavigationBar.lgf_Reload()
            self.lgf_NavigationBar.lgf_RightButton?.addTarget(self, action: #selector(rightBtnSelect(_:)), for: .touchUpInside)
        }
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
            super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        }
    
    convenience init() {
        let nibNameOrNil = String(describing: Self.Type.self)
        //考虑到xib文件可能不存在或被删，故加入判断
        if Bundle.main.path(forResource: nibNameOrNil, ofType: "nib") != nil
        {
            self.init(nibName: nibNameOrNil, bundle: nil)
        }else{
        
            self.init(nibName: nil, bundle: nil)
            self.view.backgroundColor = .white
        
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        if !isScreenPanPopEnabled {
            navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        }
        navigationController?.interactivePopGestureRecognizer?.addTarget(self, action: #selector(screenPanPopEnabled(_:)))
        if isHorizontalScreen {
            if UIDevice.current.orientation == .portrait {
                LGF_ShouldAutorotate.lgf.lgf_IsShouldAutorotate = true
                UIDevice.lgf_SwitchNewOrientation(.landscapeRight)
                LGF_ShouldAutorotate.lgf.lgf_IsShouldAutorotate = false
            }
        } else {
            LGF_ShouldAutorotate.lgf.lgf_IsShouldAutorotate = true
            UIDevice.lgf_SwitchNewOrientation(.portrait)
            LGF_ShouldAutorotate.lgf.lgf_IsShouldAutorotate = false
        }
    }
    
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//        if !isScreenPanPopEnabled {
//            navigationController?.interactivePopGestureRecognizer?.isEnabled = true
//        }
//        navigationController?.interactivePopGestureRecognizer?.removeTarget(self, action: #selector(screenPanPopEnabled(_:)))
//        if isHorizontalScreen {
//            if UIDevice.current.orientation == .landscapeRight {
//                DispatchQueue.main.async {
//                    LGF_ShouldAutorotate.lgf.lgf_IsShouldAutorotate = true
//                    UIDevice.lgf_SwitchNewOrientation(.portrait)
//                    LGF_ShouldAutorotate.lgf.lgf_IsShouldAutorotate = false
//                }
//            }
//        }
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 11.0, *) {} else {
            self.navigationController?.automaticallyAdjustsScrollViewInsets = false
            self.automaticallyAdjustsScrollViewInsets = false
        }
        LGFCrash.add(delegate: self)
        view.backgroundColor = UIColor.white
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        debugPrint("视图控制器已释放")
    }
    
    @objc func leftBtnSelect() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc func leftBtnLongSelect() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc func rightBtnSelect(_ sender: UIButton) {
        
    }
    
    @objc func screenPanPopEnabled(_ sender: UIScreenEdgePanGestureRecognizer) {}
}

extension BaseVC: LGFCrashDelegate {
    func lgf_CrashDidCatchCrash(with model: LGFCrashModel) {
        let type: String = model.type! == .exception ? "exception" : "signal"
        let name: String = model.name!
        let reason: String = model.reason!
        let appinfo: String = model.appinfo!
        let callStack: String = model.callStack!
        let date: NSDate = NSDate()
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "YYYY/MM/dd hh:mm:ss SS"
        let strNowTime = timeFormatter.string(from: date as Date) as String
        let path = NSHomeDirectory() + "/Documents/LGF_EWE_Exception.txt"
        var readData = ""
        do {
            readData = try String.init(contentsOf: URL.init(fileURLWithPath: path))
        } catch { }
        let url: String = "\n\n" + "🤖️(异常错误报告):" + "\n异常类型:" + type + "\n异常名字:" + name + "\n异常原因:" + reason + "\n" + appinfo + "\n异常发生时间:" + strNowTime + "\nCrash调用栈(CallStack):\n" + callStack
        let new = readData + url
        do {
            try new.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
        } catch { }
    }
}
